

package com.hazelcast.client.impl.spi.impl.discovery;

import com.hazelcast.client.impl.connection.AddressProvider;
import com.hazelcast.client.impl.connection.Addresses;
import com.hazelcast.client.impl.management.ClientConnectionProcessListenerRegistry;
import com.hazelcast.cluster.Address;
import com.hazelcast.cluster.Member;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;

public class RemoteAddressProvider implements AddressProvider {

    private final Callable<Map<Address, Address>> getAddresses;
    private final boolean usePublic;
    private volatile Map<Address, Address> privateToPublic = new HashMap<>();

    public RemoteAddressProvider(Callable<Map<Address, Address>> getAddresses, boolean usePublic) {
        this.getAddresses = getAddresses;
        this.usePublic = usePublic;
    }

    @Override
    public Addresses loadAddresses(ClientConnectionProcessListenerRegistry listenerRunner) throws Exception {
        privateToPublic = getAddresses.call();
        Set<Address> addresses = privateToPublic.keySet();
        listenerRunner.onPossibleAddressesCollected(addresses);
        return new Addresses(addresses);
    }

    @Override
    public Address translate(Address address) throws Exception {
        if (address == null) {
            return null;
        }

        // if it is inside cloud, return private address otherwise we need to translate it.
        if (!usePublic) {
            return address;
        }

        Address publicAddress = privateToPublic.get(address);
        if (publicAddress != null) {
            return publicAddress;
        }

        privateToPublic = getAddresses.call();

        return privateToPublic.get(address);
    }

    @Override
    public Address translate(Member member) throws Exception {
        return translate(member.getAddress());
    }
}
